package jdbc03;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class JDBCDemo02 {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=UTF-8", "root", "123456");
        PreparedStatement ps = conn.prepareStatement("select * from test.product where pid=?");
        ps.setInt(1,8);
        ResultSet resultSet = ps.executeQuery();
        while (resultSet.next()) {
            //进行封装
            int pid = resultSet.getInt("pid");
            String pname = resultSet.getString("pname");
            double price = resultSet.getDouble("price");
            Product p = new Product(pid, pname, price);
            System.out.println(p);
        }
 resultSet.close();
        conn.close();
        ps.close();
    }
    @Test
    public void testSelectAll() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=UTF-8", "root", "123456");
        PreparedStatement ps = conn.prepareStatement("select * from test.product");
        ResultSet resultSet = ps.executeQuery();
        ArrayList<Product> products = new ArrayList<>();
        while (resultSet.next()) {
            Product p = new Product(resultSet.getInt("pid"),
                    resultSet.getString("pname"),
                    resultSet.getDouble("price")
            );
            products.add(p);
        }
        products.stream().forEach(System.out::println);
    }
}
